<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'userOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return $this->getRules();
	}


	/**
	 * Performs the AJAX validation.
	 * @param UserModel $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-model-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        
        public function actionIndex(){
            //init page value
            $pagevals = array(
                'page_title' => "Quản trị người dùng",
                'subpage_title' => 'Danh sách người dùng',
                //'action' => 'user/abc'
            );
            
            //check input params and validate input
            $config = ConfigModel::model()->findByPk('1')->attributes;
            $paging_limit_number = $config['paging_limit_number'];
            $status = isset($_GET['status']) ? $_GET['status'] : 'actived';
            $search_string = isset($_GET['search_string']) ? $_GET['search_string'] : '';
            $page_number = isset($_GET['page_number']) ? intval($_GET['page_number']) : 1;
            $gender = isset($_GET['gender']) ? $_GET['gender'] : 'all';
            $group = isset($_GET['group']) ? $_GET['group'] : 'all';
            $age = isset($_GET['age']) ? $_GET['age'] : 'all';
            $type = isset($_GET['type']) ? $_GET['type'] : 'all';
            //$gender = isset($_GET['gender']) ? $_GET['gender'] : 'all';

            
            $condition = array();
            
            //validate input
            if($page_number <= 0 || is_numeric($page_number)!= true )$page_number=1;
            if($status != 'all'){ $condition['status'] = $status; }
            if($gender != 'all'){$condition['gender'] = $gender;}
            if($group != 'all'){$condition['group'] = $group;}
            
            if($type != 'all'){
                switch ($type) {
                    case 'nomal':
                        $condition['username']='IS NOT NULL';
                        break;
                    case 'facebook':
                        $condition['facebook_id']='IS NOT NULL';
                        break;
                    case 'google':
                        $condition['google_id']='IS NOT NULL';
                        break;
                }
            }

            //convert time
            if($age != 'all'){
                $condition['birthday'] = $this->convertAge($age);
            }
            
            $sort = array('create_time'=>'desc');
            
            if($search_string == null || $search_string == ""){
                $data = UserModel::model()->getByPage($condition, $page_number, $paging_limit_number, $sort);
                $pagevals['total_row'] = UserModel::model()->countRow($condition);
            }else{
                $fields = array('username','email','fullname','identity_id','phone','address','address');
                $data = UserModel::model()->SearchMultiField($search_string, $condition, $page_number, $paging_limit_number, $fields);
                $pagevals['total_row'] = UserModel::model()->countSearch($search_string, $condition, $fields);
            }


            //process and render data 
            
            $pagevals['page_number'] = $page_number;
            $pagevals['total_page'] = UserModel::model()->countPage($pagevals['total_row'], $paging_limit_number);
            $pagevals['row_start'] = UserModel::model()->get_start_row($pagevals['total_row'], $page_number, $paging_limit_number);
            $pagevals['row_end'] = UserModel::model()->get_end_row($pagevals['total_row'], $page_number, $paging_limit_number);
            $pagevals['status'] = $status;
            $pagevals['search_string'] = $search_string;
            $pagevals['gender']= $gender;
            $pagevals['type']= $type;
            $pagevals['age']= $age;
            $pagevals['group']= $group;
            //$pagevals['gender']= $gender;


            $this->display("user/index", array('data'=>$data, 'pagevals'=>$pagevals) );
        }
        
        
        public function convertAge($age){
            $condition = array();
            switch ($age) {
                    case '1':
                        $time = mktime(0,0,0,0,0,(date('Y')-12));
                        $condition ="> $time";
                        break;
                    case '2':
                        $time1 = mktime(0,0,0,0,0,(date('Y')-12));
                        $time2 = mktime(0,0,0,0,0,(date('Y')-14));
                        $condition =array('and'=>array("> $time2","< $time1"));
                        break;
                    case '3':
                        $time1 = mktime(0,0,0,0,0,(date('Y')-14));
                        $time2 = mktime(0,0,0,0,0,(date('Y')-17));
                        $condition =array('and'=>array("> $time2","< $time1"));
                        break;
                    case '4':
                        $time1 = mktime(0,0,0,0,0,(date('Y')-17));
                        $time2 = mktime(0,0,0,0,0,(date('Y')-22));
                        $condition =array('and'=>array("> $time2","< $time1"));
                        break;
                    case '5':
                        $time = mktime(0,0,0,0,0,(date('Y')-22));
                        $condition ="<  $time";
                        break;
                }
                return $condition;
        }
        
        public function actionCreate()
	{  
            $pagevals = array(
                'page_title' => "Quản trị người dùng",
                'subpage_title' => 'Tạo người dùng mới',
                //'action' => 'user/abc'
            );
            ///--------------------------
            
            
            if(isset($_POST['username'])&& !isset($_POST['email'])){
                $user = UserModel::model()->findByAttributes(array('username'=>$_POST['username']));
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
            }
            
            else if(isset($_POST['email'])&& !isset($_POST['username'])){
                $user = UserModel::model()->findByAttributes(array('email'=>$_POST['email']));
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
            }
            
            else if(isset($_POST['username']) && isset($_POST['email'])){
                $time=time();
                $pagevals['time']=$time;
                $user = new UserModel;
                
                if($this->actionCheckinput('username') == false){
                    die ('Username duplicated');
                }
                
                if($this->actionCheckinput('email') == false){
                    die ('Email duplicated');
                }
                
                $birthday_arr = explode('/', $_POST['birthday']);
                $birthday = mktime(0,0,0,$birthday_arr[1],$birthday_arr[0],$birthday_arr[2]);
                
                
                $user->attributes = array(
                                //'id' => 'ID',
                                'username' => $_POST['username'],
                                'password' => md5($_POST['password']),
                                'fullname' => $_POST['fullname'],
                                'gender' => $_POST['gender'],
                                'phone' => $_POST['phone'],
                                'email' => $_POST['email'],
                                'address' => $_POST['address'],
                                'birthday' => $birthday,
                                'thumb'=>$_POST['thumb'],
                                //'facebook_id' =>$_POST['facebook_id'],
                                //'google_id' => $_POST['google_id'],
                                'identity_id' => $_POST['identity_id'],
                                'last_login_time' => $time,
                                'group' => 1,
                                'status' => 'waiting',
                                //'banned_date' => $_POST['banned_date'],
                                //'lifted_date' =>$_POST['lifted_date'],
                                'create_time' => $time,
                                'update_time' => $time,
                            );
                if($user->save(false)){
                    $this->redirect(array('index','status'=>'waiting'));
                }
            }
            else{
                $this->display("user/create", array('pagevals'=>$pagevals));
            }
	}
        
        public function actionEdit($id)
	{
            if(!isset($_GET['id'])){
                die('User not found');
            } 
            $pagevals = array(
                'page_title' => "Quản trị người dùng",
                'subpage_title' => 'Sửa thông tin người dùng',
                //'action' => 'user/abc'
            );
            //-------------------------------
            //get user data
            $user = UserModel::model()->findByPk($id);
            if(!is_object($user)){
                die('User not found');
            }
            
            ///--------------------------
            $time=time();
            if(isset($_POST['password'])){
                $birthday_arr = explode('/', $_POST['birthday']);
                $birthday = mktime(0,0,0,$birthday_arr[1],$birthday_arr[0],$birthday_arr[2]);
                if(isset($_POST['password'])){
                    $user->attributes = array(
                            //'id' => 'ID',
                                //'username' => $_POST['username'],
                                'password' => md5($_POST['password']),
                                'fullname' => $_POST['fullname'],
                                'gender' => $_POST['gender'],
                                'phone' => $_POST['phone'],
                                //'email' => $_POST['email'],
                                'address' => $_POST['address'],
                                'birthday' => $birthday,
                                'thumb'=>$_POST['thumb'],
                                //'facebook_id' =>$_POST['facebook_id'],
                                //'google_id' => $_POST['google_id'],
                                'identity_id' => $_POST['identity_id'],
                                'last_login_time' => $time,
                                //'group' => 1,
                                //'status' => 'waiting',
                                //'banned_date' => $_POST['banned_date'],
                                //'lifted_date' =>$_POST['lifted_date'],
                                //'create_time' => $time,
                                'update_time' => $time,
                            );
                }else{
                    $user->attributes = array(
                            //'id' => 'ID',
                                //'username' => $_POST['username'],
                                //'password' => $_POST['password'],
                                'fullname' => $_POST['fullname'],
                                'gender' => $_POST['gender'],
                                'phone' => $_POST['phone'],
                                //'email' => $_POST['email'],
                                'address' => $_POST['address'],
                                'birthday' => $birthday,
                                'thumb'=>$_POST['thumb'],
                                //'facebook_id' =>$_POST['facebook_id'],
                                //'google_id' => $_POST['google_id'],
                                'identity_id' => $_POST['identity_id'],
                                'last_login_time' => $time,
                                //'group' => 1,
                                //'status' => 'waiting',
                                //'banned_date' => $_POST['banned_date'],
                                //'lifted_date' =>$_POST['lifted_date'],
                                //'create_time' => $time,
                                'update_time' => $time,
                            );
                }
                
                        
                if($user->save(false)){
                    $this->redirect(array('user/index'));
                }
            }
            $this->display("user/edit", array('pagevals'=>$pagevals,'data'=>$user->attributes));
        }
        
        public function checkinput(){
            if(isset($_POST['username'])){
                $user = UserModel::model()->findByAttributes(array('username'=>$_POST['username']));
                if(is_object($user)){echo 'false'; return false;}
                else {echo 'true'; return true;}
            }
            
            if(isset($_POST['email'])){
                $user = UserModel::model()->findByAttributes(array('email'=>$_POST['email']));
                if(is_object($user)){echo 'false';}
                else {echo 'true';}
            }
        }
        
        public function doAcion($status,$data){
            $i = 0;
            $time = time();
            $game_id = explode(';', $data);
            if(sizeof($game_id) == 0){
                echo 0;
            }
            else{
                foreach($game_id as $value){
                    if($value != 0){
                        $result = UserModel::model()->modify($value,array('status'=>$status,'update_time'=>$time));
                        if($result == true){
                            $i++;
                        }
                    }
                }
                echo $i;
            }
        }
        
        
        public function actionCopy(){
            if(isset($_POST['game_id'])){
                $i = 0;
                $game_id = explode(';', $_POST['game_id']);
                if(sizeof($game_id) == 0){
                    echo 0;
                }
                else{
                    foreach($game_id as $value){
                        if($value != 0){
                            $result = UserModel::model()->copy($value);
                            if($result == true){
                                $i++;
                            }
                        }
                    }
                    echo $i;
                }
            }
        }
        
        public function actionBanned(){
            
            if(isset($_POST['banned_ids'])){
                $this->doAcion('banned', $_POST['banned_ids']);
            }
            
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'banned','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionWaiting(){
            if(isset($_POST['waiting_ids'])){
                $this->doAcion('waiting', $_POST['waiting_ids']);
            }
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'waiting','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionActive(){
            if(isset($_POST['active_ids'])){
                $this->doAcion('actived', $_POST['active_ids']);
            }
            
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'active','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionBlock(){
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'blocked','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionRestore(){
            if(isset($_POST['restore_ids'])){
                $this->doAcion('actived', $_POST['restore_ids']);
            }
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'waiting','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionLock(){
            if(isset($_POST['locked_ids'])){
                $this->doAcion('locked', $_POST['locked_ids']);
            }
            
            if(isset($_POST['id'])){
                $result = UserModel::model()->modify($_POST['id'],array('status'=>'locked','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function getFilterValue($fields){
            if(is_array($fields)){
                $result = array();
                foreach($fields as $key => $value){
                    $temp = UserModel::model()->getUnique($key, $value);
                    if(is_array($temp)){
                        foreach($temp as $val){
                            if($val[$key] !=null && $val[$key]!=''){
                                $result[$key][]= $val[$key];
                            }
                        }
                    }
                }
                return $result;
            }else return null;
        }
}
?>